<template>
  <div class="inventory-plan-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <el-icon><Calendar /></el-icon>
          盘点计划管理
        </h2>
        <p class="page-description">制定和管理库存盘点计划，安排盘点周期、范围和人员</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建盘点计划
        </el-button>
        <el-button @click="handleBatchImport">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出计划
        </el-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <el-card shadow="never">
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="计划名称">
            <el-input
              v-model="searchForm.planName"
              placeholder="请输入计划名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="盘点状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 150px">
              <el-option label="全部" value="" />
              <el-option label="待开始" value="pending" />
              <el-option label="进行中" value="in_progress" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="盘点类型">
            <el-select v-model="searchForm.type" placeholder="请选择类型" clearable style="width: 150px">
              <el-option label="全部" value="" />
              <el-option label="全盘" value="full" />
              <el-option label="抽盘" value="sample" />
              <el-option label="循环盘点" value="cycle" />
              <el-option label="动态盘点" value="dynamic" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon pending">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ stats.pending }}</div>
                <div class="stats-label">待开始</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon in-progress">
                <el-icon><Loading /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ stats.inProgress }}</div>
                <div class="stats-label">进行中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon completed">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ stats.completed }}</div>
                <div class="stats-label">已完成</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon total">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ stats.total }}</div>
                <div class="stats-label">总计划数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card shadow="never">
        <div class="table-header">
          <div class="table-title">盘点计划列表</div>
          <div class="table-actions">
            <el-button size="small" @click="handleRefresh">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
        
        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="planCode" label="计划编号" width="140" fixed="left">
            <template #default="{ row }">
              <el-link type="primary" @click="handleView(row)">{{ row.planCode }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="planName" label="计划名称" min-width="180" show-overflow-tooltip />
          <el-table-column prop="type" label="盘点类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getTypeTagType(row.type)">{{ getTypeText(row.type) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="warehouseName" label="盘点仓库" width="120" show-overflow-tooltip />
          <el-table-column prop="planStartDate" label="计划开始" width="110" />
          <el-table-column prop="planEndDate" label="计划结束" width="110" />
          <el-table-column prop="assignedUsers" label="负责人员" width="150">
            <template #default="{ row }">
              <div class="assigned-users">
                <el-avatar-group :max="3" size="small">
                  <el-avatar v-for="user in row.assignedUsers" :key="user.id" :src="user.avatar">
                    {{ user.name.charAt(0) }}
                  </el-avatar>
                </el-avatar-group>
                <span class="user-count">等{{ row.assignedUsers.length }}人</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="120">
            <template #default="{ row }">
              <div class="progress-container">
                <el-progress :percentage="row.progress" :stroke-width="6" :show-text="false" />
                <span class="progress-text">{{ row.progress }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="110" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleView(row)">
                查看
              </el-button>
              <el-button size="small" type="primary" link @click="handleEdit(row)" v-if="row.status === 'pending'">
                编辑
              </el-button>
              <el-button size="small" type="success" link @click="handleStart(row)" v-if="row.status === 'pending'">
                开始
              </el-button>
              <el-button size="small" type="warning" link @click="handlePause(row)" v-if="row.status === 'in_progress'">
                暂停
              </el-button>
              <el-dropdown @command="(command) => handleMoreAction(command, row)">
                <el-button size="small" type="primary" link>
                  更多<el-icon><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="copy">复制计划</el-dropdown-item>
                    <el-dropdown-item command="export">导出详情</el-dropdown-item>
                    <el-dropdown-item command="delete" v-if="row.status === 'pending'">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        class="plan-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="formData.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择盘点类型" style="width: 100%">
                <el-option label="全盘" value="full" />
                <el-option label="抽盘" value="sample" />
                <el-option label="循环盘点" value="cycle" />
                <el-option label="动态盘点" value="dynamic" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="盘点仓库" prop="warehouseId">
              <el-select v-model="formData.warehouseId" placeholder="请选择仓库" style="width: 100%">
                <el-option
                  v-for="warehouse in warehouseOptions"
                  :key="warehouse.id"
                  :label="warehouse.name"
                  :value="warehouse.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划时间" prop="planDateRange">
              <el-date-picker
                v-model="formData.planDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
        </el-col>
        </el-row>

        <el-form-item label="负责人员" prop="assignedUserIds">
          <el-select
            v-model="formData.assignedUserIds"
            multiple
            placeholder="请选择负责人员"
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="盘点范围">
          <el-radio-group v-model="formData.scopeType">
            <el-radio label="all">全部商品</el-radio>
            <el-radio label="category">按分类</el-radio>
            <el-radio label="custom">自定义</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="计划描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入计划描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Calendar,
  Plus,
  Upload,
  Download,
  Search,
  Refresh,
  Clock,
  Loading,
  CircleCheck,
  DataAnalysis,
  ArrowDown
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentRow = ref(null)
const selectedRows = ref([])
const formRef = ref(null)

// 搜索表单
const searchForm = reactive({
  planName: '',
  status: '',
  type: '',
  dateRange: []
})

// 统计数据
const stats = reactive({
  pending: 8,
  inProgress: 3,
  completed: 15,
  total: 26
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const formData = reactive({
  planName: '',
  type: '',
  warehouseId: '',
  planDateRange: [],
  assignedUserIds: [],
  scopeType: 'all',
  description: ''
})

// 表单验证规则
const formRules = {
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择盘点类型', trigger: 'change' }],
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  planDateRange: [{ required: true, message: '请选择计划时间', trigger: 'change' }],
  assignedUserIds: [{ required: true, message: '请选择负责人员', trigger: 'change' }]
}

// 选项数据
const warehouseOptions = ref([
  { id: 1, name: '主仓库' },
  { id: 2, name: '分仓库A' },
  { id: 3, name: '分仓库B' },
  { id: 4, name: '临时仓库' }
])

const userOptions = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' },
  { id: 4, name: '赵六' },
  { id: 5, name: '钱七' }
])

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑盘点计划' : '新建盘点计划'
})

// 方法
const getStatusText = (status) => {
  const statusMap = {
    pending: '待开始',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const getStatusTagType = (status) => {
  const typeMap = {
    pending: 'warning',
    in_progress: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

const getTypeText = (type) => {
  const typeMap = {
    full: '全盘',
    sample: '抽盘',
    cycle: '循环盘点',
    dynamic: '动态盘点'
  }
  return typeMap[type] || type
}

const getTypeTagType = (type) => {
  const typeMap = {
    full: 'danger',
    sample: 'warning',
    cycle: 'primary',
    dynamic: 'success'
  }
  return typeMap[type] || 'info'
}

const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        planCode: 'PD202401001',
        planName: '2024年第一季度全盘',
        type: 'full',
        status: 'in_progress',
        warehouseName: '主仓库',
        planStartDate: '2024-01-15',
        planEndDate: '2024-01-20',
        assignedUsers: [
          { id: 1, name: '张三', avatar: '' },
          { id: 2, name: '李四', avatar: '' },
          { id: 3, name: '王五', avatar: '' }
        ],
        progress: 65,
        createTime: '2024-01-10'
      },
      {
        id: 2,
        planCode: 'PD202401002',
        planName: '电子产品类抽盘',
        type: 'sample',
        status: 'pending',
        warehouseName: '分仓库A',
        planStartDate: '2024-01-25',
        planEndDate: '2024-01-26',
        assignedUsers: [
          { id: 2, name: '李四', avatar: '' },
          { id: 4, name: '赵六', avatar: '' }
        ],
        progress: 0,
        createTime: '2024-01-12'
      },
      {
        id: 3,
        planCode: 'PD202401003',
        planName: '快消品循环盘点',
        type: 'cycle',
        status: 'completed',
        warehouseName: '分仓库B',
        planStartDate: '2024-01-08',
        planEndDate: '2024-01-10',
        assignedUsers: [
          { id: 3, name: '王五', avatar: '' },
          { id: 5, name: '钱七', avatar: '' }
        ],
        progress: 100,
        createTime: '2024-01-05'
      }
    ]
    
    tableData.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    planName: '',
    status: '',
    type: '',
    dateRange: []
  })
  handleSearch()
}

const handleRefresh = () => {
  loadData()
}

const handleCreate = () => {
  isEdit.value = false
  currentRow.value = null
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  currentRow.value = row
  // 填充表单数据
  Object.assign(formData, {
    planName: row.planName,
    type: row.type,
    warehouseId: row.warehouseId,
    planDateRange: [row.planStartDate, row.planEndDate],
    assignedUserIds: row.assignedUsers.map(user => user.id),
    scopeType: 'all',
    description: row.description || ''
  })
  dialogVisible.value = true
}

const handleView = (row) => {
  ElMessage.info('查看功能开发中')
}

const handleStart = async (row) => {
  try {
    await ElMessageBox.confirm('确认开始此盘点计划？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('盘点计划已开始')
    loadData()
  } catch (error) {
    // 用户取消
  }
}

const handlePause = async (row) => {
  try {
    await ElMessageBox.confirm('确认暂停此盘点计划？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('盘点计划已暂停')
    loadData()
  } catch (error) {
    // 用户取消
  }
}

const handleMoreAction = async (command, row) => {
  switch (command) {
    case 'copy':
      ElMessage.info('复制功能开发中')
      break
    case 'export':
      ElMessage.info('导出功能开发中')
      break
    case 'delete':
      try {
        await ElMessageBox.confirm('确认删除此盘点计划？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success('删除成功')
        loadData()
      } catch (error) {
        // 用户取消
      }
      break
  }
}

const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中')
}

const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

const resetForm = () => {
  Object.assign(formData, {
    planName: '',
    type: '',
    warehouseId: '',
    planDateRange: [],
    assignedUserIds: [],
    scopeType: 'all',
    description: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    submitLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.inventory-plan-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left .page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-left .page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stats-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stats-icon.pending {
  background: linear-gradient(135deg, #f39c12, #e67e22);
}

.stats-icon.in-progress {
  background: linear-gradient(135deg, #3498db, #2980b9);
}

.stats-icon.completed {
  background: linear-gradient(135deg, #27ae60, #229954);
}

.stats-icon.total {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.assigned-users {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-count {
  font-size: 12px;
  color: #909399;
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-text {
  font-size: 12px;
  color: #606266;
  min-width: 35px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.plan-form {
  padding: 20px 0;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .inventory-plan-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-bottom: 16px;
  }
  
  .stats-section .el-col {
    margin-bottom: 16px;
  }
}
</style>